import axios from 'axios'
import { useAuthStore } from '@/store'
import { setToken } from '@/utils/auth'
import { Message } from '@arco-design/web-vue'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const instance = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: '/dev-api',
  // 超时
  timeout: 50000
})

// 请求拦截器
instance.interceptors.request.use(
  async (config) => {
    const authStore = useAuthStore()

    if (await authStore.getTokenAction()) {
      config.headers['authorization'] = await authStore.getTokenAction()
    }
    return config
  },
  (error) => {
    console.log(error)
    Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  async (res) => {
    const authStore = useAuthStore()
    if (res.headers['authorization']) {
      await authStore.setTokenAction(res.headers['authorization'])
      setToken(res.headers['authorization'])
    }
    const vo = res.data
    if (vo.code === 401) {
      Message.error(vo.msg || '登录状态已过期，请重新登录')
      authStore.clearTokenAction()
      window.location.href = '/login'
    } else if (vo.code === 403) {
      Message.error(vo.msg || '权限不足')
    } else if (vo.code === 500) {
      Message.error(vo.msg || '服务器异常')
    } else if (vo.code === 200) {
      if (vo.msg != 'success') {
        Message.success(vo?.msg)
      }
      return Promise.resolve(vo.data)
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default instance
